package service

import (
	"dao"
	"pojo/vo"
	"pojo/model"
	"constant"
	"qiniupkg.com/x/errors.v7"
	"pojo/form"
)

// 分类服务
type CategoryService struct {
	dao *dao.CategoryDao
}

func NewCategoryService(dao *dao.CategoryDao) *CategoryService {

	return &CategoryService{
		dao: dao,
	}
}

// 保存分类信息
func (this *CategoryService) InsertCategory(categoryForm *form.CategoryForm) error {

	category := &model.Category{
		Name: categoryForm.Name,
		Img:  categoryForm.Img,
		Pid:  categoryForm.Pid,
	}

	_, err := this.dao.InsertCategory(category)

	return err
}

// 查询所有父级分类
func (this *CategoryService) QueryCategoriesParents() vo.Base {
	items := make([]*vo.CategoryVo, 0)

	// 查询所有父类
	categories, _ := this.dao.ListCategory(0)

	for _, category := range categories {
		categoryVo := this.transformCategory(category)
		items = append(items, categoryVo)
	}

	result := constant.SUCCESS
	result.Info = items

	return result
}

// 树形结构查询分类信息
func (this *CategoryService) QueryCategories() vo.Base {

	items := make([]*vo.CategoryVo, 0)

	// 查询所有父类
	categories, _ := this.dao.ListCategory(0)

	for _, category := range categories {

		categoryVo := this.transformCategory(category)
		// 根据父类查询子类信息
		children, _ := this.dao.ListCategory(uint64(category.ID))

		if len(children) > 0 {

			citems := make([]*vo.CategoryVo, 0)

			for _, cate := range children {
				cvo := this.transformCategory(cate)
				citems = append(citems, cvo)
			}

			categoryVo.Children = citems
		}

		items = append(items, categoryVo)
	}

	result := constant.SUCCESS
	result.Info = items

	return result
}

// 把model转换为vo
func (this *CategoryService) transformCategory(category *model.Category) *vo.CategoryVo {

	vo := &vo.CategoryVo{
		Id:   uint64(category.ID),
		Name: category.Name,
		Img:  category.Img,
		Pid:  category.Pid,
	}

	return vo
}

// 删除分类信息
func (this *CategoryService) DeleteCategory(id uint64) error {

	children, _ := this.dao.ListCategory(id)

	if len(children) > 0 {
		return errors.New("该分类下拥有子分类无法删除")
	}

	return this.dao.DeleteCategory(id)
}

// 根据ID查询分类信息
func (this *CategoryService) FindCategory(id uint64) (*model.Category, error) {

	return this.dao.FindCategory(id)
}

// 修改分类信息
func (this *CategoryService) UpdateCategory(categoryForm *form.CategoryForm) error {

	category := &model.Category{
		Name: categoryForm.Name,
		Img:  categoryForm.Img,
		Pid:  categoryForm.Pid,
	}

	category.ID = uint(categoryForm.Id)

	_, err := this.dao.UpdateCategory(category)

	return err
}
